package com.yykj.template.server.controller;

import com.qcloud.cos.utils.Md5Utils;
import com.yykj.common.enums.ResultEnums;
import com.yykj.common.exception.NormalException;
import com.yykj.common.util.LocalUploadFile;
import com.yykj.common.vo.ResultVO;
import com.yykj.template.server.client.dto.ConsultationReportDTO;
import com.yykj.template.server.service.TemplateService;
import com.yykj.template.server.util.ImageTool;
import freemarker.template.TemplateException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;

/**
 * tll
 * 2020/5/28
 */
@Api(tags = "模板生成图片")
@RestController
@RequestMapping("/template")
@Slf4j
public class TemplateController {
    @PostMapping("/generate")
    @ApiOperation("问诊结论")
    public ResultVO<String> generateConsultationReport(@RequestBody ConsultationReportDTO dto) throws IOException, TemplateException {
        return ResultVO.success(templateService.generateConsultationReport(dto));
    }

    @GetMapping("/hospital/sign")
    @ApiOperation("生成医院印章图片")
    public ResultVO<String> getHospitalSign(@RequestParam(name = "hospitalName", required = true) String hospitalName) {
        String savePath = "./temp/";
        String saveName = Md5Utils.md5Hex(hospitalName) + ".png";
        File dir = new File(savePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String circlePath = savePath + "initCircle.png";
        File circleFile = new File(circlePath);
        if (!circleFile.exists()) {
            LocalUploadFile.downLoadRemoteFile("https://file.yaoyanglao.com/static/template/initCircle.png", circlePath);
        }
        ImageTool.buildHospitalSign(hospitalName, savePath + saveName, circlePath);

        String s = LocalUploadFile.uploadFile(new File(savePath + saveName));
        return ResultVO.success(s);

    }

    @ApiOperation("生成处方笺图片")
    @GetMapping("/prescription/note/{prescriptionId}")
    public ResultVO<String> generatePrescriptionNote(@PathVariable String prescriptionId) {
        try {
            return ResultVO.success(templateService.generatePrescriptionNote(prescriptionId));
        } catch (Exception e) {
            throw new NormalException(ResultEnums.TEMP_GENERATE_ERROR,e.getMessage());
        }
    }


    private TemplateService templateService;

    @Autowired
    public void setTemplateService(TemplateService templateService) {
        this.templateService = templateService;
    }
}
